package cn.uai.activiti8.approval.cmd;

import com.uai.activiti7.cache.GlobalCache;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.cmd.NeedsActiveTaskCmd;

import java.util.List;

/**
 * @desc
 * @author uai
 * @since 2025/7/28 10:09
 * @version 1.0
 */
public abstract class AbstractRejectCmd<T> extends NeedsActiveTaskCmd<T> {

    public AbstractRejectCmd(String taskId) {
        super(taskId);
    }

    /**
     * 找到结束节点
     * @param process 流程模型
     * @return 结束节点
     */
    public EndEvent findEndEvent(Process process, String processDefinitionId) {
        if (GlobalCache.END_EVENT_ELEMENT_CACHE.containsKey(processDefinitionId)) {
            return (EndEvent) GlobalCache.END_EVENT_ELEMENT_CACHE.get(processDefinitionId);
        }
        for (FlowElement element : process.getFlowElements()) {
            if (element instanceof EndEvent) {
                GlobalCache.END_EVENT_ELEMENT_CACHE.put(processDefinitionId, element);
                return (EndEvent) element;
            }
        }
        return null;
    }

    /**
     * 获取当前 UserTask 节点的前一个 UserTask 节点。
     *
     * 比如有流程： a(发起) -> b(审批1) -> c(审批2) -> d(审批3) -> e(结束)
     *
     * 如果 d(审批3) 驳回至上一个节点 c(审批2)，只需要找到 c(审批2) 的 ActivityId 就可以了
     * @param userTaskHistoricActivities 历史 UserTask 节点集合
     * @param currentActivityId 当前活跃的 UserTask 的id
     * @return 上一节点 UserTask 的id
     */
    public int getPrevActivityIndex(List<HistoricActivityInstance> userTaskHistoricActivities, String currentActivityId) {
        int prevActivityIndex = 0;
        if (userTaskHistoricActivities.size() > 1) {
            int currentActivityIndex = 0;
            for (int i = 0; i < userTaskHistoricActivities.size(); i++) {
                HistoricActivityInstance historicActivityInstance = userTaskHistoricActivities.get(i);
                if (historicActivityInstance.getActivityId().equals(currentActivityId)) {
                    currentActivityIndex = i;
                    break;
                }
            }
            prevActivityIndex = currentActivityIndex - 1;
        }
        return prevActivityIndex;
    }
}
